package com.example.qsindusty.jmm_spline.ChooseDriver;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.qsindusty.jmm_spline.Config.Config;
import com.example.qsindusty.jmm_spline.R;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.yixin.ystartlibrary.base.BaseAppCompatActivity;
import com.yixin.ystartlibrary.base.BaseRecyclerAdapter;
import com.yixin.ystartlibrary.utils.DensityUtil;
import com.yixin.ystartlibrary.utils.DialogUtils;
import com.yixin.ystartlibrary.utils.GeneralPreferencesUtils;
import com.yixin.ystartlibrary.utils.LoadingDialogUtils;
import com.yixin.ystartlibrary.utils.LogUtils;
import com.yixin.ystartlibrary.utils.StatusBarUtil;
import com.yixin.ystartlibrary.utils.ToastUtils;
import com.yixin.ystartlibrary.widget.DiverItemDecoration;
import com.yixin.ystartlibrary.widget.EmptyRecyclerView;
import com.yixin.ystartlibrary.widget.HintDialog;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ChooseDriverActivity extends BaseAppCompatActivity implements ChooseDContact.View {

    @BindView(R.id.materialHeader)
    MaterialHeader materialHeader;
    @BindView(R.id.recyclerview)
    EmptyRecyclerView recyclerview;
    @BindView(R.id.iv_empty)
    ImageView ivEmpty;
    @BindView(R.id.empty_text)
    TextView emptyText;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    ChoosePresenter mPresenter;
    String row = Config.row;//默认为10条
    String page = Config.page;
    String token;
    DriverAdapter driverAdapter ;
    int mPosition ;
    EditText editText ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_driver);
        editText = new EditText(this);
        LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
                (int) (DensityUtil.getWidth(mActivity)*0.6), LinearLayout.LayoutParams.WRAP_CONTENT);
        layout.gravity= Gravity.CENTER ;
        editText.setLayoutParams(layout);
        editText.setBackgroundResource(R.drawable.textinouteidtetext);
        editText.setHint("司机姓名");
        editText.setTextSize(12);
        editText.setSingleLine();
        mToolbarTitle.setVisibility(View.GONE);
        StatusBarUtil.immersive(this.getWindow());
        StatusBarUtil.setPaddingSmart(this, mToolBar);
        setEnabledNavigation(true);
        mToolBar.addView(editText);
        ButterKnife.bind(this);
    }

    @Override
    protected void init() {
        mPosition=getIntent().getIntExtra(Config.count,-1);
        LogUtils.i("mposition=="+mPosition);
        bindPresenter();
        initview();
        initrefresh();
        token = GeneralPreferencesUtils.getSharedPreference(mActivity, Config.token, null);
        getD(token, row, page);
    }


    /**
     * 加载初始化
     */
    private void initrefresh() {
        refreshLayout.setEnableScrollContentWhenLoaded(false);
        refreshLayout.setEnableAutoLoadmore(false);
        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                String searckey= editText.getText().toString().trim();
                if (TextUtils.isEmpty(searckey)){
                    getD(token, row, page);
                }
                else {
                    mPresenter.getDriver(GeneralPreferencesUtils.getSharedPreference(mActivity,Config.token,null),row,page,searckey);
                }


            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = "1";
                String searckey= editText.getText().toString().trim();
                if (TextUtils.isEmpty(searckey)){
                    getD(token, row, page);
                }
                else {
                    mPresenter.getDriver(GeneralPreferencesUtils.getSharedPreference(mActivity,Config.token,null),row,page,searckey);
                }
            }
        });
    }

    /**
     * recyclerview初始化
     */

    private void initview() {
        driverAdapter = new DriverAdapter();
        recyclerview.setLayoutManager(new LinearLayoutManager(mActivity));
        DiverItemDecoration itemDecoration = new DiverItemDecoration(DiverItemDecoration.VERTICAL);
        itemDecoration.setSize(DensityUtil.dip2px(mActivity, 0.5f));
        itemDecoration.setColor(ContextCompat.getColor(mActivity, R.color.black));
        recyclerview.addItemDecoration(itemDecoration);
        //解决ScrollView嵌套RecyclerView滑动卡帧
        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setAdapter(driverAdapter);
        emptyText.setText("试试下拉刷新");
        recyclerview.setEmptyView(LayoutInflater.from(mActivity).inflate(R.layout.item_emptyview, null));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


    /**
     * 加载DIALOG
     */
    AlertDialog alertDialog;

    @Override
    public void showLoading() {
        alertDialog = LoadingDialogUtils.create(mActivity, "");
        alertDialog.show();

    }

    @Override
    public void closeLoading() {
        if (alertDialog != null && alertDialog.isShowing())
            alertDialog.dismiss();
    }

    /**
     * 绑定presenter
     */
    @Override
    public void bindPresenter() {
        if (mPresenter == null) {
            mPresenter = new ChoosePresenter();
        }
        mPresenter.bindView(this);
    }

    /**
     * 解除绑定presenter
     */
    @Override
    public void unbindPresenter() {
        mPresenter.unbindView();
    }


    @Override
    public void getD(String token, String row, String page) {
        mPresenter.getDriver(token, row, page);
    }

    @Override
    public void getSuccessful(DriverData data) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        LogUtils.i("page"+page);
        if (page.equals("1")) {
            LogUtils.i("111111");
            driverAdapter.clearInfoList();
            driverAdapter.addInfoList(data.getData());
        } else {
            LogUtils.i("22222");
           // driverAdapter.clearInfoList();
            driverAdapter.addInfoList(data.getData());
        }
        driverAdapter.notifyDataSetChanged();
        int p = Integer.parseInt(page);
        page = String.valueOf(p + 1);
        LogUtils.e("page==" + page);
    }

    @Override
    public void getNomore(String msg) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();

        if (TextUtils.equals(page, "1")) {
            driverAdapter.clearInfoList();
        } else {

        }
        ToastUtils.showLongToast(mActivity, msg);
        driverAdapter.notifyDataSetChanged();
    }


    @Override
    public void getFrailer(String msg) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        ToastUtils.showLongToast(mActivity, msg);
    }

    @Override
    public void searchSuccessful(DriverData data) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        LogUtils.i("page"+page);
        if (page.equals("1")) {
            LogUtils.i("111111");
            driverAdapter.clearInfoList();
            driverAdapter.addInfoList(data.getData());
        } else {
            LogUtils.i("22222");

            driverAdapter.addInfoList(data.getData());
        }
        driverAdapter.notifyDataSetChanged();
        int p = Integer.parseInt(page);
        page = String.valueOf(p + 1);
        LogUtils.e("page==" + page);
    }

    @Override
    public void searchNomore(String msg) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        ToastUtils.showLongToast(mActivity, msg);
    }

    @Override
    public void searchFrailer(String msg) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        ToastUtils.showLongToast(mActivity, msg);
    }

    public class DriverAdapter extends BaseRecyclerAdapter<DriverData.DataBean, DriverAdapter.ViewHolder> {
        @Override
        protected void onBindViewHolder(int position, ViewHolder holder) {
            final DriverData.DataBean dataBean = getItem(position);
            holder.setvauels(dataBean);
            holder.tel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final HintDialog hintDialog = DialogUtils.createHintDialog(mActivity, dataBean.getXM()+":"+dataBean.getLXDH());
                    hintDialog.setTitleText("是否拨打");
                    hintDialog.setConfirmListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(Intent.ACTION_DIAL);
                            intent.setData(Uri.parse("tel:" + dataBean.getLXDH()));
                            if (intent.resolveActivity(mActivity.getPackageManager()) != null) {
                                startActivity(intent);

                            }
                            if (hintDialog!=null&&hintDialog.isShowing())
                                hintDialog.dismiss();
                        }
                    });
                    hintDialog.setConfirmText("拨打");
                    hintDialog.setCancelText("取消");
                    hintDialog.show();


                 }
            });
        }

            @Override
        protected ViewHolder getViewHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(inflate(R.layout.itme_dirvier, parent));

        }

        @Override
        protected void onBindItemClickListener(View v, int position) {
            super.onBindItemClickListener(v, position);
            Intent intent = new Intent();
            intent.putExtra("data", getItem(position));
            intent.putExtra(Config.count,mPosition);
            setResult(RESULT_OK,intent);
                finish();
        }


           class ViewHolder extends RecyclerView.ViewHolder  {
            @BindView(R.id.name)
            TextView name;
            @BindView(R.id.hetong)
            TextView hetong;
            @BindView(R.id.jiating)
            TextView jiating;
            @BindView(R.id.tel)
            ImageView tel;

            ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }
            public  void  setvauels(DriverData.DataBean driverData){
                if (!TextUtils.isEmpty(driverData.getXM()))
                    name.setText(driverData.getXM());
                if (!TextUtils.isEmpty(driverData.getHTLX()))
                    hetong.setText("合同类型："+driverData.getHTLX());
                if (!TextUtils.isEmpty(driverData.getHTLX()))
                    jiating.setText("联系电话："+driverData.getLXDH());

            }

        }
    }
    Menu mMenu;
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_search, menu);
        mMenu = menu;
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.search_icon).setVisible(true);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case  R.id.search_icon:
                page="1";
                String searckey= editText.getText().toString().trim();
                if (TextUtils.isEmpty(searckey)){
                    LogUtils.i("searckeykong");
                    getD(token, row, page);
                }
                else {
                    LogUtils.i("searckey"+searckey);
                    mPresenter.getDriver(GeneralPreferencesUtils.getSharedPreference(mActivity,Config.token,null),row,page,searckey);
                }
                break;
        }

        return false;
    }


}
